<template>
  <div class="content-list">
    <div
      v-for="item in visibleItems"
      :key="item.id"
      class="content-item"
    >
      <div class="item-header">
        <el-tag type="info" size="small">{{ item.type }}</el-tag>
        <router-link :to="`/content/${item.id}`" class="title-link">
          {{ item.title }}
        </router-link>
      </div>
      <div class="item-meta">
        <span class="author">👤 {{ item.author }}</span>
        <span class="time">🕒 {{ formatTime(item.createdAt) }}</span>
        <div class="tags" v-if="Array.isArray(item.tags)">
          <el-tag
            v-for="(tag, index) in item.tags.slice(0, 5)"
            :key="index"
            size="small"
            style="margin-right: 4px"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 加载更多按钮 -->
    <el-button
      v-if="visibleItems.length < totalItems"
      @click="loadMore"
      style="margin-top: 16px;"
    >
      加载更多
    </el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchContentList } from '@/api/content'
import { useUserStore } from '@/stores/user'
import { watch } from 'vue'

const userStore = useUserStore()
const visibleItems = ref([])
const pageSize = 10
let currentPage = 1
let totalItems = 0
let loading = false

async function loadMore() {
  if (loading) return
  loading = true

  try {
    const res = await fetchContentList({
      page: currentPage,
      pageSize: pageSize
    })

    // 如果你的接口返回是 res = { records, total }
    visibleItems.value.push(...res.records)
    totalItems = res.total
    currentPage++
  } catch (err) {
    ElMessage.error('加载内容失败')
  } finally {
    loading = false
  }
}

onMounted(() => {
  loadMore()
})

watch(
  () => userStore.user,
  () => {
    loadMore()
  },
  { immediate: true }
)

function formatTime(timestamp) {
  const date = new Date(timestamp)
  return date.toLocaleString()
}
</script>

<style scoped>
.content-list {
  max-width: 1000px;
  margin: 0 auto;
  margin-bottom: 100px;
  padding: 24px 16px;
  background: #cfdbed;
  border-radius: 12px;
}

.content-item {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  margin-bottom: 16px;
  transition: box-shadow 0.3s ease;
}

.content-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.item-header {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  margin-bottom: 6px;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  color: #666;
  font-size: 13px;
}
</style>
